#include "tcp_server.h"
#include <unistd.h>


TCP_server :: TCP_server(int portno, int maxclients)
{
    i=0;
    if (_serverSocket.getSockfd() < 0)
        _serverSocket.error("opening socket");

    //  _serv_addr.sin_addr.s_addr = INADDR_ANY;
    _serverSocket.setPortno(portno);
    // _serv_addr.sin_port = htons(_portno);

    //_serverSocket.createSocket(1, portno, _server);

    if (bind(_serverSocket.getSockfd(), (struct sockaddr *) _serverSocket.getServ_addr(), sizeof(*_serverSocket.getServ_addr())) < 0)  {
        _serverSocket.error("binding");
        exit(1);
    }

    listen(_serverSocket.getSockfd(),maxclients);
    clilen = sizeof(cli_addr);
}

int TCP_server::accept() 
{
    _new_client.push_back(::accept(_serverSocket.getSockfd(), (struct sockaddr *) &cli_addr, &clilen));

    if(_new_client[i]<0)
    {
        _serverSocket.error("accept");
        return 2;
    }
    if(fork()<0)
    {
        _serverSocket.error("fork");
        return 1;
    }
    if(fork()==0)
    {
        close(_serverSocket.getSockfd());


        return 0;
    }
    else
    {
        close (_new_client[i]);
        i++;
    }
}

void TCP_server :: write(string data)
{

    _newclient.setSockfd(_new_client[i]);
    _newclient.write(data);
}

void TCP_server::read (string &data)
{

    _newclient.setSockfd(_new_client[i]);
    _newclient.read(data);
}

TCP_server & TCP_server:: operator << (string data)
{
    this->write(data);
    return *this;
}

TCP_server & TCP_server::operator >> (string & data)
{	
    this->read(data);
    return *this;
}
